package com.antis.olsl.magic.analysis;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomsOrWarehouseDialog;
import com.antis.olsl.library.response.GetSalesroomOrWarehouseListRes;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomOrWarehouseView;
import com.antis.olsl.magic.adapter.MagicIndicatorAdapter;
import com.antis.olsl.magic.databinding.ActivityQuarterlyAnalysisBinding;
import com.trello.rxlifecycle2.LifecycleTransformer;

import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

/**
 * 四季分析
 */
@Route(path = MagicRoutePath.ACTIVITY_QUARTERLY_ANALYSIS)
public class QuarterlyAnalysisActivity extends BaseActivity<ActivityQuarterlyAnalysisBinding> implements ChooseSalesroomOrWarehouseView.ChooseSalesroomOrWarehouseListener,
        ChooseSalesroomsOrWarehouseDialog.ChooseSalesroomOrWarehouseListener, QuarterlyAnalysisContract.View, ChooseDateDialog.ChooseDateListener {

    private String[] mDataList = {"春季", "夏季", "秋季", "冬季"};
    private List<Fragment> mFragments;

    private boolean chooseAllSalesroom = true;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();
    private ChooseSalesroomsOrWarehouseDialog mDialog;

    private AnalysisFragment mSpringFragment;
    private AnalysisFragment mSummerFragment;
    private AnalysisFragment mAutumnFragment;
    private AnalysisFragment mWinterFragment;

    private QuarterlyAnalysisPresenter mPresenter;
    private ChooseDateDialog chooseDateDialog;
    private SimpleDateFormat textYearFormat = new SimpleDateFormat("yyyy年", Locale.getDefault());

    private Date startYear;
    private int intYear;

    private int mPosition = 0;
    private String salesRoomIds = "";

    @Override
    protected ActivityQuarterlyAnalysisBinding getViewBinding() {
        return ActivityQuarterlyAnalysisBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new QuarterlyAnalysisPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        initDate();
        initFragments();
        initMagicIndicator();

        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setChooseSalesroomOrWarehouseListener(this);
        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDateDialog = new ChooseDateDialog(QuarterlyAnalysisActivity.this, "选择时间", startYear, QuarterlyAnalysisActivity.this, "startDate");
                chooseDateDialog.setQuarterHint();
                chooseDateDialog.setDayHint();
                chooseDateDialog.setMonthHint();
                chooseDateDialog.setWeekHint();
            }
        });
    }

    @Override
    protected void initData() throws IllegalAccessException {

    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        startYear = calendar.getTime();

        intYear = calendar.get(Calendar.YEAR);
        viewBinding.tvDate.setText(textYearFormat.format(startYear));
    }

    private void initFragments() {
        mSpringFragment = AnalysisFragment.newInstance(salesRoomIds, intYear, 1);
        mSummerFragment = AnalysisFragment.newInstance(salesRoomIds, intYear, 2);
        mAutumnFragment = AnalysisFragment.newInstance(salesRoomIds, intYear, 3);
        mWinterFragment = AnalysisFragment.newInstance(salesRoomIds, intYear, 4);

        mFragments = new ArrayList<>(4);
        mFragments.add(mSpringFragment);
        mFragments.add(mSummerFragment);
        mFragments.add(mAutumnFragment);
        mFragments.add(mWinterFragment);

        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 0) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return mDataList[position];
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }
        };
        viewBinding.viewPager.setAdapter(adapter);

        viewBinding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                Timber.tag("hhh").e("position= " + position);
                mPosition = position;
                setLabel(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void initMagicIndicator() {
        final List<String> titleList = new ArrayList<>(4);
        titleList.add("春季");
        titleList.add("夏季");
        titleList.add("秋季");
        titleList.add("冬季");
        CommonNavigator commonNavigator = new CommonNavigator(this);
        MagicIndicatorAdapter magicIndicatorAdapter = new MagicIndicatorAdapter(this, viewBinding.viewPager);
        magicIndicatorAdapter.setTitleList(titleList);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(magicIndicatorAdapter);
        viewBinding.magicIndicator.setNavigator(commonNavigator);

        ViewPagerHelper.bind(viewBinding.magicIndicator, viewBinding.viewPager);
    }

    private void setLabel(int position) {
        switch (position) {
            case 0:
                setSpringAnalysis();
                break;
            case 1:
                setSummerAnalysis();
                break;
            case 2:
                setAutumnAnalysis();
                break;
            case 3:
                setWinterAnalysis();
                break;
            default:
                break;
        }
    }

    private void setSpringAnalysis() {
        if (mPosition == 1) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mSpringFragment) {
                mSpringFragment.loadData(salesRoomIds, intYear, 1);
            }
        }
    }

    private void setSummerAnalysis() {
        if (mPosition == 1) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mSummerFragment) {
                mSummerFragment.loadData(salesRoomIds, intYear, 2);
            }
        }
    }

    private void setAutumnAnalysis() {
        if (mPosition == 1) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mAutumnFragment) {
                mAutumnFragment.loadData(salesRoomIds, intYear, 3);
            }
        }
    }

    private void setWinterAnalysis() {
        if (mPosition == 1) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mWinterFragment) {
                mWinterFragment.loadData(salesRoomIds, intYear, 4);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }

        if (null != mDialog) {
            mDialog.dismiss();
        }
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroomOrWareList();
        } else {
            mDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, QuarterlyAnalysisActivity.this);
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getSalesroomOrWareList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onChooseSalesroomOrWarehouseListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        chooseAllSalesroom = isChooseAll;
        selectedSalesroomInfos = choosedFiledInfos;
        salesroomInfos = sourceInofs;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        loadData();
    }

    public String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {

            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if (chooseAllSalesroom) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if (chooseAllSalesroom) {
            name = "全部门店";
            chooseALL = true;
        }
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(infos);
        return ids;
    }

    private void loadData() {
        setLabel(mPosition);
    }

    @Override
    public void getSalesroomInfoListSuccess(GetSalesroomOrWarehouseListRes resp) {
        salesroomInfos.clear();
        salesroomInfos.addAll(resp.getContent());
        Timber.tag("hhh").e("GetSalesroomOrWarehouseListRes resp= " + resp.getContent().size());

        mDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, QuarterlyAnalysisActivity.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure");
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        chooseDateDialog.dismiss();
        Date tmpDate = new Date();
        try {
            tmpDate = textYearFormat.parse(year + "年");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        startYear = tmpDate;
        setYearText(year);
    }

    private void setYearText(int year) {
        intYear = year;
        viewBinding.tvDate.setText(textYearFormat.format(startYear));

        loadData();
    }
}
